﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RayDen.PowerConsole.Components
{
    public class PerformanceMeasurementController
    {
        private Stopwatch sw;

        public string Elapsed
        {
            get { return sw.Elapsed.ToString(); }
        }

        public PerformanceMeasurementController()
        {
            sw = new Stopwatch();
        }


        public void Start(Action command, string message = null)
        {
            if (!string.IsNullOrWhiteSpace(message))
            {
                Console.Write(message);
            }
            sw.Reset();
            sw.Start();
            command();
            sw.Stop();
        }

        public static string Test(Action command, string message = null, int iterations = 1)
        {
            var sw = new Stopwatch();
            if (!string.IsNullOrWhiteSpace(message))
            {
                Console.Write(message);
            }
            sw.Reset();
            sw.Start();
            for (int i = 0; i < iterations; i++)
            {
                command();
            }
            sw.Stop();

            return sw.Elapsed.ToString();
        }

        public static string Test(Action command, int threads, string message = null, int iterations = 1)
        {
            string result = string.Empty;
            var sw = new Stopwatch();

            Parallel.Invoke(new ParallelOptions() {MaxDegreeOfParallelism = threads}, () =>
            {
                if (!string.IsNullOrWhiteSpace(message))
                {
                    Console.Write(message);
                }
                sw.Reset();
                sw.Start();
                for (int i = 0; i < iterations; i++)
                {
                    command();
                }

            });
            sw.Stop();
            result = sw.Elapsed.ToString();


            return result;
        }
    }
}
